package com.hcjy.common.config;

import com.hcjy.common.JacksonObjectMapper;
import com.hcjy.common.interceptor.AuthInterceptor;
import com.hcjy.common.interceptor.CorsInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author Guqier
 * @version 1.0
 * @date 2024/1/21 下午 10:32
 */
@Slf4j
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * MVC拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CorsInterceptor());
        log.info("SYS: 注册CORS跨域拦截器");
        registry.addInterceptor(new AuthInterceptor())
                .excludePathPatterns(
                        "/auth/login",
                        "/auth/register",
                        "/auth/refreshToken",
                        "/auth/sendPhoneVerifyCode",
                        "/auth/verifyPhoneCode");
        log.info("SYS: 注册Auth权限验证拦截器");
    }

    /**
     * 扩展MVC的消息转换器
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //  设置对象转换器，底层使用Jackson将Java对象转换为json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        // 将上面的消息转换器对象追加到MVC框架的转换器集合中
        converters.add(0, messageConverter);
    }
}
